package com.zhengming.reactor;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

import static java.lang.Thread.sleep;

public class FutureTest {
    private static ThreadPoolExecutor poolExecutor = null;

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("demo-pool-%d").build();
        poolExecutor = new ThreadPoolExecutor(5, 5,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

        System.out.println("main   start");
        completableFutureTest();
        System.out.println("main   end");
    }

    public static void completableFutureTest() throws ExecutionException, InterruptedException {
        CompletableFuture<String> futureImg = CompletableFuture.supplyAsync(() -> {
            System.out.println("查询图片信息");
            return "查询图片信息";
        }, poolExecutor);

        CompletableFuture<String> futureAttr = CompletableFuture.supplyAsync(() -> {
            System.out.println("查询属性信息");
            return "查询属性信息";
        }, poolExecutor);

        CompletableFuture<String> futureBrand = CompletableFuture.supplyAsync(() -> {
            try {
                sleep(3000);
                System.out.println("查询介绍信息");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "查询介绍信息";
        }, poolExecutor);

        //futureImg.get();
        //futureAttr.get();
        //futureBrand.get(); //调用get会阻塞当前主线程,当时如果只需要Img和Attr完成才做某件事情时就显得Brand代码冗余和费时
        // 因为这样大家都是等待最长的那个完成，才完成阻塞,可以使用allOf来选择堵塞个别线程任务


        CompletableFuture<Void> allOf = CompletableFuture.allOf(futureImg, futureAttr, futureBrand);
        allOf.get(); //等待所有选中future完成

        //System.out.println(futureImg.get() + "" + futureAttr.get() + "" + futureBrand.get());

    }
}
